/**
 * 全局设置模块（持久化到 localStorage）
 */
const STORAGE_KEY = "app_settings_v1";

function load() {
    try {
        const raw = localStorage.getItem(STORAGE_KEY);
        if (raw) return JSON.parse(raw);
    } catch (e) {
        console.error(e);
    }
    return {
        // editor related (legacy)
        options: {
            lineNumbers: true,
            lineWrapping: true,
            styleActiveLine: true,
            extraKeys: "Ctrl",
            theme: "default",
        },
        // ui settings
        siteAccent: "#7c5cff",
        figFloat: true,
        figPos: null, // {x,y}
        figMin: false,
    };
}

function save(state) {
    try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
    } catch (e) {
        console.error(e);
    }
}

const state = load();

const mutations = {
    SAVE_OPTIONS(state, params) {
        state.options = { ...params };
        save(state);
    },
    SET_SITE_ACCENT(state, color) {
        state.siteAccent = color;
        save(state);
    },
    SET_FIG_FLOAT(state, enabled) {
        state.figFloat = !!enabled;
        save(state);
    },
    SET_FIG_POS(state, pos) {
        state.figPos = pos;
        save(state);
    },
    SET_FIG_MIN(state, min) {
        state.figMin = !!min;
        save(state);
    },
};

const actions = {
    saveOptions({ commit }, params) {
        commit("SAVE_OPTIONS", params);
    },
    setAccent({ commit }, color) {
        commit("SET_SITE_ACCENT", color);
    },
    setFigFloat({ commit }, enabled) {
        commit("SET_FIG_FLOAT", enabled);
    },
    setFigPos({ commit }, pos) {
        commit("SET_FIG_POS", pos);
    },
    setFigMin({ commit }, min) {
        commit("SET_FIG_MIN", min);
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};
